package com.kun.framework.data.persistence;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.kun.framework.core.util.JacksonUtil;
import com.kun.framework.data.persistence.enums.PersistenceFileTypeEnum;
import com.kun.framework.data.persistence.rule.FileCreateRule;

/**
 * json文件数据持久化
 *
 * @author gzc
 * @since 2024/8/21
 **/
public abstract class JsonDataPersistence<D> extends DefaultAbstractDataPersistence<D> {

    public JsonDataPersistence(String baseStorageDir,
                               FileCreateRule fileCreateRule) {
        super(baseStorageDir, fileCreateRule, PersistenceFileTypeEnum.JSON);
    }

    @Override
    public D dataStrConvertObj(String jsonStr) {
        D result = null;
        JsonNodeType jsonStrType = JacksonUtil.getJsonStrType(jsonStr);
        if (jsonStrType != null) {
            TypeReference<D> reference = new TypeReference<>() {
            };
            if (JsonNodeType.ARRAY == jsonStrType) {
                result = JacksonUtil.parseArray(jsonStr, reference);
            } else if (JsonNodeType.OBJECT == jsonStrType || JsonNodeType.POJO == jsonStrType) {
                result = JacksonUtil.parseObject(jsonStr, reference);
            }
        }
        return result;
    }
}
